<template>
    <div class="app-container">

        <div class="app-container-left">
            <tree ref="tree" @set-tree-data="setTreeData" @go_menu="go_menu" />
        </div>

        <div class="app-container-right">

            <div :class="['filter-container',{'open':formState}]">
                <!-- <a v-if="screenState" class="form-more" href="#" title="更多筛选" @click="formState = !formState"><i
                        :class="formState ? 'el-icon-caret-top':'el-icon-caret-bottom'" /></a> -->
                <!-- <el-form ref="form" :model="form" @keyup.enter.native="handleFilter()" label-width="80px"> -->

                <!-- 筛选框需要些双份 一种是没有展开状态下的  只有主要的几个筛选框，另一种是全部的筛选框都展示 也就是展开状态下的 -->
                <!-- 没有展开状态下的筛选框 -->
                <el-form v-if="!formState" ref="filtrateForm" :inline="true" :model="filtrateForm" label-width="80px">

                    <el-form-item label="收费项目:" prop="parkId">
                        <el-select v-model="filtrateForm.project_id" placeholder="请选择" style="width:160px;">
                            <el-option v-for="item in project_options" :key="item.id" :label="item.itemsName" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="开始/结束" prop="beginTime_endTime">
                        <el-date-picker v-model="filtrateForm.beginTime_endTime" style="width:260px" type="monthrange" format="yyyy 年 MM 月"
                            value-format="yyyy-MM" range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item v-if="!formState">
                        <el-button class="filter-item" @click="handleFilter">
                            查询
                        </el-button>
                        <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                            :disabled="dataListSelections.length <= 0" @click="handleCreateSide()">去收款</el-button>
                        <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                            :disabled="!this.TreeData_all.id" @click="handleCreate">生成周期账单</el-button>
                        <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                            :disabled="!this.TreeData_all.id" @click="handleCreate1">添加临时应收</el-button>
                    </el-form-item>
                </el-form>

                <!-- 展开状态下的筛选框 -->
                <el-form v-if="formState" ref="form" :inline="true" :model="filtrateForm" label-width="80px">
                    <el-form-item label="收费项目:" prop="parkId">
                        <el-select v-model="filtrateForm.project_id" placeholder="请选择" style="width:160px;">
                            <el-option v-for="item in project_options" :key="item.id" :label="item.itemsName" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="开始/结束" prop="beginTime_endTime">
                        <el-date-picker v-model="filtrateForm.beginTime_endTime" style="width:260px" type="monthrange" format="yyyy 年 MM 月"
                            value-format="yyyy-MM" range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份">
                        </el-date-picker>
                    </el-form-item>

                </el-form>
                <div v-if="formState" class="filter-button">
                    <el-button class="filter-item" @click="handleFilter">
                        查询
                    </el-button>
                    <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                        :disabled="dataListSelections.length <= 0" @click="handleCreateSide()">去收款</el-button>
                    <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                        :disabled="!this.TreeData_all.id" @click="handleCreate">生成周期账单</el-button>
                    <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                        :disabled="!this.TreeData_all.id" @click="handleCreate1">添加临时应收</el-button>
                </div>

            </div>

            <div :class="['table',{'open':formState}]">
                <div class="table-container">
                    <el-table :key="tableKey" v-loading="listLoading" row-key="menuId" height="100%" :data="list" border fit
                        highlight-current-row style="width: 100%;" @selection-change="selectionChangeHandle">

                        <!-- type="selection" -->
                        <el-table-column label="" header-align="center" align="center" width="50">
                            <el-table-column type="selection" label="合计" align="center" header-align="center" width="50"></el-table-column>
                        </el-table-column>

                        <el-table-column prop="houseName" header-align="center" align="center" label="房屋名称" width="180">
                            <el-table-column label="" header-align="center" align="center">
                                <template
                                    slot-scope="scope">{{scope.row.buildingName}}-{{scope.row.unitName}}-{{scope.row.floorName}}-{{scope.row.houseName}}</template>
                            </el-table-column>
                        </el-table-column>
                        <el-table-column prop="itemsName" header-align="center" align="center" label="收费项目">
                            <el-table-column prop="itemsName" label="" header-align="center" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column prop="customerName" header-align="center" align="center" label="客户名称">
                            <el-table-column prop="customerName" label="" header-align="center" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column prop="billBeginTime" header-align="center" align="center" label="账单开始日期">
                            <el-table-column prop="billBeginTime" label="" header-align="center" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column prop="billEndTime" header-align="center" align="center" label="账单结束日期">
                            <el-table-column prop="billEndTime" label="" header-align="center" align="center"></el-table-column>
                        </el-table-column>

                        <el-table-column prop="billAllMoney" header-align="center" align="center" label="应收金额(元)">
                            <el-table-column :label="'合计：'+billAllMoney_" header-align="center" align="center">
                                <template slot-scope="scope">{{ scope.row.billAllMoney  }}</template>
                            </el-table-column>
                        </el-table-column>

                        <el-table-column prop="billFreeMoney" header-align="center" align="center" label="减免金额(元)">
                            <el-table-column :label="'合计：'+billFreeMoney_" header-align="center" align="center">
                                <template slot-scope="scope">{{ scope.row.billFreeMoney }}</template>
                            </el-table-column>
                        </el-table-column>

                        <el-table-column prop="billRealMoney" header-align="center" align="center" label="实际应收金额(元)">
                            <el-table-column :label="'合计：'+billRealMoney_" header-align="center" width="140" align="center">
                                <template slot-scope="scope">{{ scope.row.billRealMoney }}</template>
                            </el-table-column>

                        </el-table-column>

                        <!-- <el-table-column prop="state" header-align="center" align="center" label="房屋状态">
                            <template slot-scope="scope">{{ scope.row.state | houseStateFilter  }}</template>
                        </el-table-column>
                        <el-table-column prop="updateTime" header-align="center" align="center" width="180" label="最后编辑时间">
                            <template slot-scope="scope">{{ scope.row.updateTime  }}</template>
                        </el-table-column>
                        <el-table-column prop="updateUserName" header-align="center" align="center" label="编辑人" /> -->
                        <el-table-column header-align="center" align="center" label="操作">
                            <el-table-column label="" header-align="center" align="center" width="150">
                                <template slot-scope="scope">
                                    <el-button v-permission="['sys:config:update']" type="text" size="small"
                                        @click="handleCreateSide(scope.row)">
                                        收款
                                    </el-button>
                                    <el-button v-permission="['sys:config:update']" type="text" size="small"
                                        @click="handleCreate2(scope.row)">
                                        减免
                                    </el-button>
                                    <el-button v-permission="['sys:config:delete']" type="text" size="small"
                                        @click="deleteHandle(scope.row)">作废
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table-column>

                    </el-table>
                </div>
            </div>

            <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        </div>

        <!-- tree新增修改 -->
        <!-- <add-or-update-tree v-if="addOrUpdateVisibletree" ref="addOrUpdatetree" @getList="handleFilter" @getTree="getTree" /> -->
        <!-- 生成周期账单-弹框 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @getList="handleFilter" />
        <!-- 添加临时应收-弹框 -->
        <add-or-update1 v-if="addOrUpdateVisible1" ref="addOrUpdate1" @getList="handleFilter" />
        <!-- 减免-弹框 -->
        <add-or-update2 v-if="addOrUpdateVisible2" ref="addOrUpdate2" @getList="handleFilter" />
        <!-- 侧面弹框 -->
        <side-dialog v-if="SideDialogVisible" ref="SideDialog" @getList="handleFilter"></side-dialog>

        <!-- //阅读量弹框  -->
        <!-- <el-dialog :visible.sync="dialogPvVisible" title="读取数据">
            <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
                <el-table-column prop="key" label="Channel" />
                <el-table-column prop="pv" label="Pv" />
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
            </span>
        </el-dialog> -->

    </div>
</template>

<script>

import { getFinancebilldetail, getChargeList, saveCancleBill, createFinancebillbatch } from '@/api/charge'// 请求数据  收费标准
import { daleteHouseTree, getCustomerByHouseId, getTreeHouseList } from '@/api/assets'// 请求数据  固定资产
import { HouseExportExcel, downloadMock, HouseImportExcel } from '@/api/index'// 请求数据
import permission from '@/directive/permission/index.js' // 权限判断指令
import { houseState, houseType, houseFunction } from '@/utils/enum' //字典
import { toDate } from '@/utils'

import Pagination from '@/components/Pagination' // secondary package based on el-pagination 分页组件
import Tree from './components/tree' // 树形组件
import SideDialog from './components/SideDialog' //侧面弹框组件
import AddOrUpdateTree from './add-or-update-tree' // tree新增或者修改弹框
import AddOrUpdate from './add-or-update' // 生成周期账单
import AddOrUpdate1 from './add-or-update1' // 添加临时应收
import AddOrUpdate2 from './add-or-update2' // 减免-弹框




export default {
    name: 'LayoutTable',
    components: { Pagination, Tree, AddOrUpdate, AddOrUpdate1, AddOrUpdate2, AddOrUpdateTree, SideDialog },
    directives: { permission }, // 指令
    // 过滤 {{row.status | statusFilte}}
    // html代码中，{{}}中实现filters顺序是 {{参数 | filters函数 | filters函数 | ...}}
    // 后面可以多个filters函数，前面filters函数return的结果是后面filters函数的参数。
    // 并且可以在过滤函数后面加上（）里面加上其他的参数。如 filterTwo('同学')
    filters: {
        // statusFilter (status) {
        //     const statusMap = {
        //         published: 'success',
        //         draft: 'info',
        //         deleted: 'danger'
        //     }
        //     return statusMap[status]
        // },
        toData (data) {
            return toDate(data)
        },
        typeFilter (type) {
            return calendarTypeKeyValue[type]
        },
        houseStateFilter (status) {
            let map = houseState;
            return map[status]
        }
    },
    data () {
        return {
            screenState: false, // 筛选框是否展示下拉按钮
            formState: false, // 筛选框的 开合
            // 筛选框的 form 表单
            filtrateForm: {
                project_id: '',//收费项目
                beginTime_endTime: '',//开始结束月份

                // name: '',
                // house_state: "",//房屋状态
                // house_function: "",//房屋功能
            },
            rules: { // 表单验证
                // type: [{ required: true, message: 'type is required', trigger: 'change' }],
                // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
                // title: [{ required: true, message: 'title is required', trigger: 'blur' }]
            },
            dataListSelections: [], // 批量删除选中
            // 树形选择结果
            treeData: {
                type: '',//类型
                id: '', //房屋id
                parkId: '', //园区id
                buildingId: '',//楼栋id
                unitId: '',//单元id
                floorId: '',//楼层id
            },
            TreeData_all: {},//完整的树形选择信息
            houses_customer: {},//房间下的客户信息
            tableKey: 0,
            list: [], // 表格数据
            total: 0, // 总条数
            listLoading: true, // 表格加载数据时的 loading
            listQuery: { // 表格当前页 和 当前页的展示数量
                page: 1,
                limit: 20
            },

            project_options: [],//项目list


            // addOrUpdateVisibletree: false, // 楼栋 新增和修改 弹框展示隐藏
            addOrUpdateVisible: false,
            addOrUpdateVisible1: false,
            addOrUpdateVisible2: false,
            SideDialogVisible: false,


            // dialogPvVisible: false, //阅读量弹框
            // pvData: [], //阅读量弹框里面的表格数据
            // downloadLoading: false, // 导出按钮 的 loading
            // downloadLoading1: false, // 下载模板 的 loading
            // action: HouseImportExcel(),//导入地址
            // headers: {},//导入参数
        }
    },
    computed: {
        //三个合计金额
        billAllMoney_ () {
            if (this.list.length < 1) return "0";
            let numberS = this.list.map(item => {
                return item.billAllMoney ? item.billAllMoney * 1 : 0
            })
            let number = eval(numberS.join("+")).toString()
            return number
        },
        billFreeMoney_ () {
            if (this.list.length < 1) return "0";
            let numberS = this.list.map(item => {
                return item.billFreeMoney ? item.billFreeMoney * 1 : 0
            })
            let number = eval(numberS.join("+")).toString()
            return number
        },
        billRealMoney_ () {
            if (this.list.length < 1) return "0";
            let numberS = this.list.map(item => {
                return item.billRealMoney ? item.billRealMoney * 1 : 0
            })
            let number = eval(numberS.join("+")).toString()
            return number
        }

    },
    created () {
        this.getList()
        this.getCharge()
    },
    methods: {
        // 树选择
        setTreeData (data) {
            console.log('树形选择结果', data)
            if (!data.name) return;
            this.treeData.id = data.id
            this.treeData.parkId = data.parkId
            this.treeData.type = data.type
            this.TreeData_all = data
            // this.treeData.buildingId = data.buildingId
            // this.treeData.unitId = data.unitId
            // this.treeData.floorId = data.floorId
            //查询房间下的客户信息
            this.getCustomer()
            this.handleFilter()
        },

        // 获取表格数据
        async getList () {
            this.listLoading = true
            // 筛选+分页
            const params = Object.assign({
                houseId: this.treeData.id,
                itemsId: this.filtrateForm.project_id,
                billBeginTime: this.filtrateForm.beginTime_endTime[0],
                billEndTime: this.filtrateForm.beginTime_endTime[1],
                state: 3 //1 作废   2 已收账单   3应收账单

            }, this.listQuery)
            // 请求
            const res = await getFinancebilldetail(params).catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            console.log(data)

            this.list = data.list
            this.total = data.totalCount
            this.listLoading = false
        },
        // 重新获取表格数据 页码归为1
        handleFilter () {
            this.listQuery.page = 1
            this.getList()
        },
        //选择房间后-查询房间下的客户信息
        async getCustomer () {
            let params = {
                houseId: this.treeData.id
            }
            const res = await getCustomerByHouseId(params).catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            this.houses_customer = data ? data : {};
            console.log("客户信息", data)
        },
        //获取项目list
        async getCharge () {
            // let params = {
            //     parkId: this.temp.parkId
            // }
            const res = await getChargeList().catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            this.project_options = [{ id: '', itemsName: '' }].concat(data)
            console.log("项目list", data)
            // this.project_change(this.temp.project_id)
        },
        //刷新tree
        getTree () {
            this.$refs.tree.getTree()
        },
        go_menu (e) {
            // if (['delete_building', 'delete_unit', 'delete_floor'].includes(e.type)) {
            //     this.handleDeleteTree(e.node)
            // }
            // if (['add_building', 'add_unit', 'add_floor'].includes(e.type)) {
            //     this.handleCreate(e.node)
            // }
            // if (['up_building', 'up_unit', 'up_floor'].includes(e.type)) {
            //     this.handleUpdate(e.node)
            // }
        },
        // // Tree新增数据-打开弹框
        // handleCreate_tree (param) {
        //     this.addOrUpdateVisibletree = true
        //     // let param = param
        //     this.$nextTick(() => {
        //         this.$refs.addOrUpdatetree.init('create', param)
        //     })
        // },
        // // Tree修改 -- 打开弹框
        // handleUpdate_tree (row) {
        //     this.addOrUpdateVisibletree = true
        //     this.$nextTick(() => {
        //         this.$refs.addOrUpdatetree.init('update', row)
        //     })
        // },
        //删除tree
        // async handleDeleteTree (data) {
        //     // let param = {
        //     //     id: data.id
        //     // }
        //     this.$confirm(`确定对[${data.storeyName}]进行[删除]操作?`, '提示', {
        //         confirmButtonText: '确定',
        //         cancelButtonText: '取消',
        //         type: 'warning'
        //     }).then(async () => {
        //         // 提交删除
        //         const { code, message } = await daleteHouseTree({}, data.id)
        //         // 成功
        //         this.$message({
        //             message: '操作成功',
        //             type: 'success',
        //             duration: 1500,
        //             onClose: () => {
        //                 this.handleFilter()// 刷新数据
        //                 this.getTree()
        //             }
        //         })
        //     })
        // },
        // 收款台-侧面弹框
        handleCreateSide (param) {
            this.SideDialogVisible = true
            const idS = param ? [param.id] : this.dataListSelections.map(item => { return item.id })
            this.$nextTick(() => {
                this.$refs.SideDialog.init('收款台', { idS })
            })
        },
        // 生成周期账单-打开弹框
        handleCreate () {
            if (!this.TreeData_all.id) {
                this.$message({
                    message: '请先选择房屋',
                    type: 'warning',
                    duration: 1000,
                    onClose: () => {
                    }
                })
                return
            };
            if (!this.houses_customer.id) {
                this.$message({
                    message: '房间下没有客户无法进行此操作',
                    type: 'warning',
                    duration: 1500,
                    onClose: () => {
                    }
                })
                return
            }
            this.addOrUpdateVisible = true
            let param = {
                parkId: this.TreeData_all.parkId,
                buildingId: this.TreeData_all.buildingId,
                unitId: this.TreeData_all.unitId,
                floorId: this.TreeData_all.floorId,
                id: this.TreeData_all.id,
                parkName: this.TreeData_all.parkName,
                buildingName: this.TreeData_all.buildingName,
                unitName: this.TreeData_all.unitName,
                floorName: this.TreeData_all.floorName,
                name: this.TreeData_all.name,
            }
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init('create', param)
            })
        },
        // 添加临时应收-打开弹框
        handleCreate1 () {
            if (!this.TreeData_all.id) {
                this.$message({
                    message: '请先选择房屋',
                    type: 'warning',
                    duration: 1000,
                    onClose: () => {
                    }
                })
                return
            };
            if (!this.houses_customer.id) {
                this.$message({
                    message: '房间下没有客户无法进行此操作',
                    type: 'warning',
                    duration: 1500,
                    onClose: () => {
                    }
                })
                return
            }
            this.addOrUpdateVisible1 = true
            let param = {
                parkId: this.TreeData_all.parkId,
                buildingId: this.TreeData_all.buildingId,
                unitId: this.TreeData_all.unitId,
                floorId: this.TreeData_all.floorId,
                id: this.TreeData_all.id,
                parkName: this.TreeData_all.parkName,
                buildingName: this.TreeData_all.buildingName,
                unitName: this.TreeData_all.unitName,
                floorName: this.TreeData_all.floorName,
                name: this.TreeData_all.name,
                customerName: this.houses_customer.customerName,
                customerId: this.houses_customer.id,
                area: this.TreeData_all.area,
            }
            this.$nextTick(() => {
                this.$refs.addOrUpdate1.init('create', param)
            })
        },
        // 作废-打开弹框
        handleCreate2 (param) {
            this.addOrUpdateVisible2 = true
            // let param = param
            this.$nextTick(() => {
                this.$refs.addOrUpdate2.init('create', param)
            })
        },

        // 修改 -- 打开弹框
        // handleUpdateHouse (row) {
        //     this.addOrUpdateVisible = true
        //     this.$nextTick(() => {
        //         this.$refs.addOrUpdate.init('update', row)
        //     })
        // },
        // 批量删除数据 - 多选
        selectionChangeHandle (val) {
            this.dataListSelections = val
        },
        // 作废账单
        async deleteHandle (data) {
            const idS = data ? [data.id] : this.dataListSelections.map(item => { return item.id })
            const nameS = data ? [data.itemsName] : this.dataListSelections.map(item => { return item.itemsName })
            let v = await this.$confirm(`确定对[${nameS.join('、')}]进行[删除]操作?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })

            // 提交删除
            let params = {
                idList: idS
            }
            const { code, message } = await saveCancleBill(params)
            // 成功
            this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                    this.handleFilter()// 刷新数据
                }
            })
        },
        //导入成功
        // handleSuccess (data, file, fileList) {
        //     if (data && data.code === 200) {
        //         this.$message({
        //             message: "操作成功",
        //             type: "success",
        //             duration: 1500,
        //             onClose: () => {
        //                 this.handleFilter()// 刷新数据
        //             }
        //         });
        //     } else {
        //         this.$message.error(data.message);
        //     }
        // },
        //下载模板
        // handleDownloadMock () {
        //     this.downloadLoading1 = true
        //     // let params = `?&page=${this.listQuery.page}&limit=${this.listQuery.limit}`
        //     // const url = `${process.env.VUE_APP_BASE_API}/assets/house/exportExcel${params}`
        //     const url = downloadMock('房屋导入模板.xls')
        //     const link = document.createElement('a')
        //     link.style.display = 'none'
        //     link.href = url
        //     // link.setAttribute('download', 'xxx.xlsx');
        //     document.body.appendChild(link)
        //     link.click()
        //     document.body.removeChild(link)

        //     this.downloadLoading1 = false
        // },
        //导出 后台接口
        // handleDownload () {
        //     this.downloadLoading = true
        //     // let params = `?&page=${this.listQuery.page}&limit=${this.listQuery.limit}`
        //     // const url = `${process.env.VUE_APP_BASE_API}/assets/house/exportExcel${params}`
        //     const url = HouseExportExcel(this.listQuery)
        //     const link = document.createElement('a')
        //     link.style.display = 'none'
        //     link.href = url
        //     // link.setAttribute('download', 'xxx.xlsx');
        //     document.body.appendChild(link)
        //     link.click()
        //     document.body.removeChild(link)
        //     this.downloadLoading = false
        // },

    }
}
</script>
<style lang="scss" scoped>
//表格布局的注释：
//$rowLength 这个变量表示了 筛选的搜索框会有多少行，由于在不同宽度显示器下 所占行数会不一定 ，所以下面使用媒体查询 做兼容
//最小兼容至 1366
@import '~@/styles/layout-table.scss';
$rowLength: 2;
@media all and (min-width: 1659px) {
    $rowLength: 1;
    @include calculation($rowLength: $rowLength);
}
@media all and (max-width: 1659px) {
    $rowLength: 1;
    @include calculation($rowLength: $rowLength);
}
</style>
